package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.db.conn;

public class admin_Pass extends HttpServlet {


    public admin_Pass() {
        super();
    }


    public void destroy() {
        super.destroy();
    }

    //修改密码
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        //得到用户的登录信息
        HttpSession session = request.getSession();
        String aid=(String) session.getAttribute("adminId");//用户ID


        if(aid==null) //是否登录
        {
            out.println("<script>");
            out.println("alert('对不起，请先登录！');");
            out.println("window.top.location='login.jsp'");
            out.println("</script>");
        }
        else
        {
            //得到要更新的密码信息
            String pwd1=request.getParameter("txt_pwd");
            String pwd2=request.getParameter("txt_pwd2");
            String pwd3=request.getParameter("txt_pwd3");

            //判断新密码和确认密码是否一致
            if (!pwd2.equals(pwd3))
            {
                out.println("<script>");
                out.println("alert('新密码和确认密码不一致，请重新输入！');window.history.go(-1);");
                out.println("</script>");
                return ;
            }

            //声明数据库操作类
            conn cn=new conn();

            //根据管理员编号和原密码得到管理员信息
            String sql="select * from admin where aid="+aid+" and pwd='"+pwd1+"' ";

            ResultSet rs=cn.query(sql);

            try {
                if(rs.next()){  //原密码正确

                    //更新新密码
                    sql="update admin set pwd='"+pwd2+"' where aid="+aid;
                    cn.update(sql);

                    out.println("<script>");
                    out.println("alert('恭喜您：修改成功！');");
                    out.println("window.location='admin/admin/pass.jsp'");
                    out.println("</script>");
                }
                else //原密码不正确
                {
                    out.println("<script>");
                    out.println("alert('对不起，原密码错误，请重新输入！');");
                    out.println("window.location='admin/admin/pass.jsp'");
                    out.println("</script>");
                }

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }

        out.flush();
        out.close();
    }


    public void init() throws ServletException {
        // Put your code here
    }

}



